﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CLFramework.Web.UI
{
    /// <summary>
    /// Inherit from ASB.MES.Web.UI.Page , will authenticate if user has right to access the page.
    /// </summary>
    public abstract class AuthorisedPage : Page
    {
        ///// <summary>
        ///// 
        ///// </summary>
        //public MesPrincipal CurrentMesPrincipal
        //{
        //    get
        //    {
        //        return MesAuthenticationModule.Current.CurrentUser;
        //    }
        //}

        #region OnInit

        /// <summary>
        /// Initializes data model and controls.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            //Check if timeout
            CheckTimeOut();
            //check if user have the permission to access this page.
            Authenticate();
            base.OnInit(e);
        }

        #endregion

        #region Authenticate

        /// <summary>
        /// Authenticate user, check if user have the permission to access this page.
        /// </summary>
        private void Authenticate()
        {
            if (!Context.User.Identity.IsAuthenticated && this.Request.Url.AbsoluteUri.IndexOf("Login.aspx") < 0)
            {
                System.Diagnostics.Debug.WriteLine("MES Page:" + this.Request.Url.AbsoluteUri);
                Response.Redirect("~/Login.aspx?ReturnUrl=" + Server.UrlEncode(Request.Url.PathAndQuery));
                return;
            }
            //bool authentication = false;

            //IModules modules = Users.Current.MenuSource as IModules;
            //if (modules != null)
            //{
            //    string relativeCurrentPath = Request.AppRelativeCurrentExecutionFilePath;
            //    relativeCurrentPath = relativeCurrentPath.TrimStart('~', '/');

            //    IFunctionInfo function = modules.GetFunctionByPath(relativeCurrentPath);
            //    if (function != null && function.Enable)
            //    {
            //        functionInfo = function;
            //        functionNo = function.No;
            //        authentication = true;
            //    }
            //}
            //if (!authentication)
            //{
            //    //Not authenticated!
            //    Throw("Web_Error_0001");
            //}
        }

        #endregion

    }
}
